package com.athuahua.spzx.service.impl;

import com.athuahua.spzx.entity.ProductSku;
import com.athuahua.spzx.vo.ProductSkuPageVo;
import com.athuahua.spzx.feignapi.ProductFeignClient;
import com.athuahua.spzx.utils.BaseContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.athuahua.spzx.entity.UserBrowseHistory;
import com.athuahua.spzx.service.UserBrowseHistoryService;
import com.athuahua.spzx.mapper.UserBrowseHistoryMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author huahua
* @description 针对表【user_browse_history(用户浏览记录表)】的数据库操作Service实现
* @createDate 2024-08-26 18:27:28
*/
@Service
public class UserBrowseHistoryServiceImpl extends ServiceImpl<UserBrowseHistoryMapper, UserBrowseHistory>
    implements UserBrowseHistoryService{

    @Resource
    private UserBrowseHistoryMapper userBrowseHistoryMapper;

    @Resource
    private ProductFeignClient productSkuFeignClient;


    @Override
    public ProductSkuPageVo findUserBrowseHistoryPage(Integer page, Integer size) {
        ProductSkuPageVo result = new ProductSkuPageVo();
        List<ProductSku> list = new ArrayList<>();

        IPage<UserBrowseHistory> iPage = new Page<>(
                page,
                size
        );
        IPage<UserBrowseHistory> IPage = userBrowseHistoryMapper.selectPage(iPage, new LambdaQueryWrapper<UserBrowseHistory>()
                .eq(UserBrowseHistory::getUserId, BaseContext.getCurrentId())
                .orderByDesc(UserBrowseHistory::getUpdateTime));
        IPage.getRecords().forEach(item -> {
            Long skuId = item.getSkuId();
            ProductSku productSku = productSkuFeignClient.getBySkuId(skuId);
            list.add(productSku);
        });
        result.setList(list);
        result.setTotal((int) IPage.getTotal());


        return result;
    }

    @Override
    public void saveUserBrowseHistory(Long skuId) {
        UserBrowseHistory userBrowseHistory = new UserBrowseHistory();
        userBrowseHistory.setSkuId(skuId);
        userBrowseHistory.setUserId(BaseContext.getCurrentId());
        userBrowseHistoryMapper.insert(userBrowseHistory);
    }
}




